package com.example.luozizhao.eprxdemo.utils;

import android.content.SharedPreferences.Editor;
import android.text.format.Time;


import com.example.luozizhao.eprxdemo.net.bean.DateInfo;
import com.example.luozizhao.eprxdemo.net.bean.Lunar;
import com.example.luozizhao.eprxdemo.net.response.login.UserLoginRespBean;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimeUtils {
	public static int getCurrentYear() {
		Time t = new Time();
		t.setToNow();
		return t.year;
	}

	public static int getCurrentMonth() {
		Time t = new Time();
		t.setToNow();
		return t.month + 1;
	}

	public static int getCurrentDay() {
		Time t = new Time();
		t.setToNow();
		return t.monthDay;
	}

	/**
	 * 时间字符串转换成时间戳
	 * @param 时间字符串
	 * @return 时间戳
	 */
	public static long getTime(String user_time) {
		long timestamp = 0;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d;
		try {  
			d = sdf.parse(user_time);  
			timestamp = d.getTime();  
		} catch (ParseException e) {
			e.printStackTrace();  
		}  
		return timestamp;  
	}  

	/**
	 * 转换秒成字符串  yyyy年MM月dd日   HH:mm:ss
	 */
	public static String convertSecondsToString(long timeStamp){
		SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
		Date d1=new Date();
		d1.setTime(timeStamp * 1000);
		String t1=format.format(d1);
		return t1;
	}

	/**
	 * 转换秒成字符串 yyyy-MM-dd HH:mm:ss
	 */
	public static String convertSecondsToTimeStr(long timeStamp){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1=new Date();
		d1.setTime(timeStamp * 1000);
		String t1=format.format(d1);
		return t1;
	}

	/**
	 * 转换毫秒成字符串 yyyy-MM-dd HH:mm:ss
	 */
	public static String convertMillSecondsToTimeStr(long timeStamp){
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d1=new Date();
		d1.setTime(timeStamp);
		String t1=format.format(d1);
		return t1;
	}

	/**
	 * @param timeStr yyyy-MM-dd HH:mm:ss格式的时间
	 * @return 时间戳（毫秒）
	 */
	public static long getTimeMills(String timeStr) {
		//		String re_time = null;  
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d;
		try {  
			d = sdf.parse(timeStr);  
			long l = d.getTime();  
			return l;
		} catch (ParseException e) {
			e.printStackTrace();  
		}  
		return 0;  
	}
	/**
	 * 获取指定格式的时间
	 * @param time long类型的时间
	 * @param sf SimpleDateFormat格式
	 * @return
	 */
	public static String getFormatTime(long time, SimpleDateFormat sf){
		String timeString=null;
		if(null==sf){
			sf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		}
		Date d=new Date(time);
		timeString=sf.format(d);
		return timeString;
	}

	/**
	 * 把时间保存到本地
	 */
	public static void saveTimeToLocal(UserLoginRespBean.ScheduItemBean scheduItem, Editor edit){
		long scheduleDate = scheduItem.getScheduleDate();
		Calendar instance2 = Calendar.getInstance();
		int curYear = instance2.get(Calendar.YEAR);
		int curMonth = instance2.get(Calendar.MONTH);
		int curDay = instance2.get(Calendar.DAY_OF_MONTH);

		instance2.setTimeInMillis(scheduleDate);
		int year = instance2.get(Calendar.YEAR);
		int month = instance2.get(Calendar.MONTH);
		int day = instance2.get(Calendar.DAY_OF_MONTH);

		if(curYear == year && curMonth == month && curDay == day){
			String startTime = scheduItem.getStartTime();
			String endTime = scheduItem.getEndTime();
			edit.putString("startTime", startTime);
			edit.putString("endTime", endTime);
			edit.putLong("scheduleDate", scheduleDate);
		}
	}

	public static int getTimeByPosition(int position, int originYear,
			int originMonth, String type) {
		int year = originYear, month = originMonth;
		if (position > 500) {
			for (int i = 500; i < position; i++) {
				month++;
				if (month == 13) {
					month = 1;
					year++;
				}
			}
		} else if (position < 500) {
			for (int i = 500; i > position; i--) {
				month--;
				if (month == 0) {
					month = 12;
					year--;
				}
			}
		}
		if (type.equals("year")) {
			return year;
		}
		return month;
	}

	public static int getWeekDay(String date) {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			calendar.setTime(sdf.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			dayOfWeek = 0;
		} else {
			dayOfWeek -= 1;
		}
		return dayOfWeek;
	}

	public static boolean isLeapYear(int year) {
		if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0) {
			return true;
		}
		return false;
	}

	public static int getDaysOfMonth(int year, int month) {
		switch (month) {
		case 0:
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		default:
			if (isLeapYear(year)) {
				return 29;
			}
			return 28;
		}
	}

	public static String getFormatDate(int year, int month) {
		String formatYear = year + "";
		String formatMonth = "";
		if (month < 10) {
			formatMonth = "0" + month;
		} else {
			formatMonth = month + "";
		}
		return formatYear + "-" + formatMonth + "-01";
	}

	public static String getFormatDate(int year, int month, int day) {
		String formatYear = year + "";
		String formatMonth = "";
		String formatDay = "";
		if (month < 10) {
			formatMonth = "0" + month;
		} else {
			formatMonth = month + "";
		}
		if (day < 10) {
			formatDay = "0" + day;
		} else {
			formatDay = day + "";
		}
		return formatYear + "-" + formatMonth + "-" + formatDay;
	}

	public static List<DateInfo> initCalendar(String formatDate, int month)
			throws Exception {
		int dates = 1;
		int year = Integer.parseInt(formatDate.substring(0, 4));
		int[] allDates = new int[42];
		for (int i = 0; i < allDates.length; i++) {
			allDates[i] = -1;
		}
		int firstDayOfMonth = TimeUtils.getWeekDay(formatDate);
		int totalDays = TimeUtils.getDaysOfMonth(year, month);
		for (int i = firstDayOfMonth; i < totalDays + firstDayOfMonth; i++) {
			allDates[i] = dates;
			dates++;
		}

		List<DateInfo> list = new ArrayList<DateInfo>();
		DateInfo dateInfo;
		for (int i = 0; i < allDates.length; i++) {
			dateInfo = new DateInfo();
			dateInfo.setDate(allDates[i]);
			if (allDates[i] == -1) {
				dateInfo.setNongliDate("");
				dateInfo.setThisMonth(false);
				dateInfo.setWeekend(false);
			} else {
				String date = TimeUtils.getFormatDate(year, month, allDates[i]);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				long time = sdf.parse(date).getTime();
				Lunar lunar = new Lunar(time);
				if (lunar.isSFestival()) {
					dateInfo.setNongliDate(lunar.getSFestivalName());
					dateInfo.setHoliday(true);
				} else {
					if (lunar.isLFestival()
							&& lunar.getLunarMonthString().substring(0, 1)
							.equals("闰") == false) {
						dateInfo.setNongliDate(lunar.getLFestivalName());
						dateInfo.setHoliday(true);
					} else {
						if (lunar.getLunarDayString().equals("初一")) {
							dateInfo.setNongliDate(lunar.getLunarMonthString()
									+ "月");
						} else {
							dateInfo.setNongliDate(lunar.getLunarDayString());
						}
						dateInfo.setHoliday(false);
					}
				}
				dateInfo.setThisMonth(true);
				int t = getWeekDay(getFormatDate(year, month, allDates[i]));
				if (t == 0 || t == 6) {
					dateInfo.setWeekend(true);
				} else {
					dateInfo.setWeekend(false);
				}
			}
			list.add(dateInfo);
		}

		int front = DataUtils.getFirstIndexOf(list);
		int back = DataUtils.getLastIndexOf(list);
		int lastMonthDays = getDaysOfMonth(year, month - 1);
		int nextMonthDays = 1;
		for (int i = front - 1; i >= 0; i--) {
			list.get(i).setDate(lastMonthDays);
			lastMonthDays--;
		}
		for (int i = back + 1; i < list.size(); i++) {
			list.get(i).setDate(nextMonthDays);
			nextMonthDays++;
		}
		return list;
	}

	/**
	 * 把毫秒，转换成 ：。如：03:10
	 * 
	 * @param millisencond
	 * @return
	 */
	public static String convertMilliSecondToMinute2(int millisencond) {
		int oneMinute = 1000 * 60;
		int minutes = millisencond / oneMinute;
		int sencond = (millisencond - minutes * oneMinute) / 1000;
		return getNum(minutes) + ":" + getNum(sencond);
	}

	/**
	 * 把秒，转换成 ：。如：03:10
	 * 
	 * @param millisencond
	 * @return
	 */
	public static String convertSecondToMinute2(int seconds) {
		int oneMinute = 60;
		int minutes = seconds / oneMinute;
		int mSecond = seconds - minutes * oneMinute;
		return getNum(minutes) + ":" + getNum(mSecond);
	}

	public static String getNum(int num) {
		if (num >= 10) {
			return "" + num;
		} else {
			return "0" + num;
		}
	}

	/**
	 * 获取某年某月的第一天
	 * 
	 * @Title:getFisrtDayOfMonth
	 * @Description:
	 * @param:@param year
	 * @param:@param month
	 * @param:@return
	 * @return:String
	 * @throws
	 */
	public static String getFisrtDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		// 设置年份
		cal.set(Calendar.YEAR, year);
		// 设置月份
		cal.set(Calendar.MONTH, month - 1);
		// 获取某月最小天数
		int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
		// 设置日历中月份的最小天数
		cal.set(Calendar.DAY_OF_MONTH, firstDay);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String firstDayOfMonth = sdf.format(cal.getTime());

		return firstDayOfMonth;
	}

	/**
	 * 获取某年某月的第一天
	 * 
	 * @Title:getFisrtDayOfMonth
	 * @Description:
	 * @param:@param year
	 * @param:@param month
	 * @param:@return
	 * @return:String
	 * @throws
	 */
	public static String getLastDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		// 设置年份
		cal.set(Calendar.YEAR, year);
		// 设置月份
		cal.set(Calendar.MONTH, month - 1);
		// 获取某月最小天数
		int firstDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		// 设置日历中月份的最小天数
		cal.set(Calendar.DAY_OF_MONTH, firstDay);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String firstDayOfMonth = sdf.format(cal.getTime());

		return firstDayOfMonth;
	}

	/**
	 * 时间戳
	 * 
	 * @return
	 */
	public static String getTimestamp() {
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		return String.valueOf(ts.getTime());
	}

	/**
	 * 把毫秒转化成日期
	 * 
	 * @param dateFormat
	 *            (日期格式，例如：MM/ dd/yyyy HH:mm:ss)
	 * @param millSec
	 *            (毫秒数)
	 * @return
	 */
	public static String transferLongToDate(String dateFormat, Long millSec) {
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = new Date(millSec);
		return sdf.format(date);
	}

	/**
	 * 获取当前年
	 * 
	 * @return
	 */
	public static int todayYear() {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		return year;
	}

	/**
	 * 获取当前月
	 * 
	 * @return
	 */
	public static int todayMonth() {
		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH) + 1;
		return month;
	}

	/**
	 * 获取前一个月或者后一个月第一天
	 * 
	 * @return
	 */
	public static String getMonthZQOne(int monthIndex) {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, monthIndex); // 得到前一个月 -1 后一个月 +1
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		System.out.println("===============first:" + first);
		return first;
	}

	/**
	 * 获取前一个月或者后一个月最后一天
	 * 
	 * @return
	 */
	// public static String getMonthZQLast(int lastIndex) {
	// // 获取当前月最后一天
	// Calendar ca = Calendar.getInstance();
	// ca.set(Calendar.DAY_OF_MONTH, lastIndex); // 设置为0，为前月的最后一天
	// // 如果2不知道是不是下个月的最后一天
	// String last = format.format(ca.getTime());
	// System.out.println("===============last:" + last);
	// return last;
	// }

	/**
	 * 获取下个月的最后一天
	 * 
	 * @param lastIndex
	 * @return
	 */
	public static String getMonthXYYLast(int lastIndex) {
		Calendar c = Calendar.getInstance();
		// c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);
		c.add(Calendar.MONTH, lastIndex);
		c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
		// c.set(Calendar.DAY_OF_MONTH, 0);
		String last = format.format(c.getTime());
		System.out.println("下个月的最后一天: " + last);
		return last;
	}

	// Calendar c = Calendar.getInstance();
	// System.out.println(c.getTime());
	// c.set(Calendar.MONTH, c.get(Calendar.MONTH)+1);
	// c.set(Calendar.DAY_OF_MONTH, 1);
	// System.out.println("下个月的第一天: " + c.getTime());
	// c.set(Calendar.MONTH, c.get(Calendar.MONTH)+1);
	// c.set(Calendar.DAY_OF_MONTH, 0);
	// System.out.println("下个月的最后一天: " + c.getTime());

	/**
	 * 获取当前月第一天
	 * 
	 * @return
	 */
	static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	public static String getMonthOne() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 0);
		c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
		String first = format.format(c.getTime());
		System.out.println("===============first:" + first);
		return first;
	}

	/**
	 * 获取当前月last
	 * 
	 * @return
	 */
	public static String getMonthLast() {
		// 获取当前月最后一天
		Calendar ca = Calendar.getInstance();
		ca.set(Calendar.DAY_OF_MONTH,
				ca.getActualMaximum(Calendar.DAY_OF_MONTH));
		String last = format.format(ca.getTime());
		System.out.println("===============last:" + last);
		return last;
	}

	/**
	 * 获取今天时间
	 */
	public static String getToday() {
		String today = format.format(new Date());
		return today;
	}

	// 将long字符串转换成格式时间输出
	public static String getChangString(String time) {
		Date date = new Date(Long.parseLong(time));
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		time = formatter.format(date);
		return time;
	}

	/**
	 * 获取今天的日期
	 */
	public static String getTodayDate() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		String format2 = df.format(new Date());// new Date()为获取当前系统时间
		return format2;
	}

	/**
	 * 获取今天的日期
	 */
	public static String getTodayHHmmDate() {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");// 设置日期格式
		String format2 = df.format(new Date());// new Date()为获取当前系统时间
		return format2;
	}

	/**
	 * 获取今天的日期
	 */
	public static String getYearMonth() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");// 设置日期格式
		String format2 = df.format(new Date());// new Date()为获取当前系统时间
		return format2;
	}

	/**
	 * 比较大小，判断早中晚
	 * 
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static String timeBj(String startTime, String endTime) {
		// java 比较时间大小
		// String s1="00:00:00";
		String s8 = "08:00:00";
		String s16 = "16:00:00";
		String s24 = "24:00:00";
		String s00 = "00:00:00";

		// String s1="2008-01-25 09:12:09";
		// String s2="2008-01-29 09:12:11";
		// java.text.DateFormat df=new
		// java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		java.util.Calendar c1 = java.util.Calendar.getInstance();
		java.util.Calendar c2 = java.util.Calendar.getInstance();
		// try
		// {
		// c1.setTime(df.parse(s1));
		// c2.setTime(df.parse(s2));
		// }catch(java.text.ParseException e){
		// System.err.println("格式不正确");
		// }

		// 如果时间段在
		// int result = startTime.compareTo(s1);
		// int result2 = endTime.compareTo(s1);

		if (startTime.compareTo(s16) == 0 && endTime.compareTo(s24) == 0) {
			return "晚";
		} else if (startTime.compareTo(s8) == 0 && endTime.compareTo(s16) == 0) {
			return "中";
		} else if (startTime.compareTo(s24) == 0 && endTime.compareTo(s8) == 0) {
			return "早";
		}else if (startTime.compareTo(s00) == 0 && endTime.compareTo(s8) == 0) {
			return "早";
		}
		else {
			return "特";
		}

		// 当开始时间和结束的时间相等的时候
		// if(startTime.compareTo(s1)==0&&endTime.compareTo(s8)==0){
		// return "早";
		// }else if(startTime.compareTo(s8)==0&&endTime.compareTo(s16)==0){
		// return "中";
		// }else if(startTime.compareTo(s16)==0&&endTime.compareTo(s24)==0){
		// return "晚";
		// }

		// int result=c1.compareTo(c2);
		// if(result==0)
		// System.out.println("c1相等c2");
		// else if(result<0)
		// System.out.println("c1小于c2");
		// else
		// System.out.println("c1大于c2");

	}

	/**
	 * 年月日比较大小
	 * @param DATE1
	 * @param DATE2
	 * @return
	 */
	public static int compare_date(String DATE1, String DATE2) {

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				System.out.println("dt1 在dt2前");
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				System.out.println("dt1在dt2后");
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	/**
	 * 年月日时分秒比较大小
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int compareDateTime(String date1, String date2) {

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			Date dt1 = df.parse(date1);
			Date dt2 = df.parse(date2);
			if (dt1.getTime() > dt2.getTime()) {
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}
	/**
	 * 分钟换算秒
	 */
	private static final int MIN_=60;
	/**
	 * 小时换算秒
	 */
	private static final int HOUR_=3600;
	/**
	 * 天
	 */
	private static final int DAY_=86400;

	/**
	 * 年
	 */
	private static final int YEAR_=31536000;
	/**
	 * 日期格式
	 */
	private static DateFormat df = new SimpleDateFormat("MM-dd HH:mm");

	/**
	 * 获取距离现在的时间段长短
	 * @param orTime 操作时间
	 * @return
	 */
	public static String getTimeFromNow(long orTime ){
		if(orTime<=0){
			return null;
		}
		String returnTime=null;
		long currentTime= System.currentTimeMillis();
		/**
		 * 时间算成秒
		 */
		long differ=(currentTime-orTime)/1000;

		if(differ<MIN_){
			returnTime="刚刚";
		}else if(differ>MIN_&&differ<HOUR_){
			int num=(int) (differ/MIN_);
			returnTime=num+"分钟前";
		}else if(differ>HOUR_&&differ<DAY_){
			int num=(int) (differ/HOUR_);
			returnTime=num+"小时前";
		}else if(differ>DAY_&&differ<YEAR_){

			returnTime=df.format(new Date(orTime));
		}else{
			int num=(int) (differ/YEAR_);
			returnTime=num+"年前";
		}
		return returnTime;
	}

	/**
	 * 获取距离现在的时间段长短
	 * @param orTime 操作时间
	 * @return
	 */
	public static String getTimeFormat(long orTime ){
		if(orTime<=0){
			return "";
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String time = df.format(orTime);
		return time;
	}

	/**
	 * 判断距离现在时间是否少于1分钟
	 * @param orTime 操作时间
	 * @return
	 */
	public static boolean isTimeLessThanMin(long orTime){
		if(orTime<=0){
			return true;
		}
//		String returnTime=null;
		long currentTime= System.currentTimeMillis();
		/**
		 * 时间算成秒
		 */
		long differ=(currentTime-orTime)/1000;

		if(differ<MIN_){
//			returnTime="刚刚";
			return true;
		}else{
			return false;
		}
	}

}
